package com.ruoyi.common.core.utils;

import com.ruoyi.common.core.utils.bean.BASE64DecodedMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * Base64工具类
 */
public class Base64Utils {

    public static Boolean isBase64(String base64) {

        if (base64.lastIndexOf(",") != -1) {
            base64 = base64.substring(base64.lastIndexOf(",") + 1);

        }

        try {
            BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(base64)));

            if (null == bufImg) {
                return false;

            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;

        }

    }


    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStrs[1]);

            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }

            return new BASE64DecodedMultipartFile(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}


